package cn.myweixin.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import cn.myweixin.po.Mark;
import cn.myweixin.po.MarkKey;
import cn.myweixin.po.NoticourseKey;
import cn.myweixin.po.SignKey;
import cn.myweixin.po.Trainee;
import cn.myweixin.service.impl.MarkImpl;
import cn.myweixin.service.impl.NoticeCourseImpl;
import cn.myweixin.service.impl.NoticeImpl;
import cn.myweixin.service.impl.SignImpl;
 
import cn.myweixin.service.impl.TraineeImpl;

import cn.myweixin.util.WeixinUtil;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/user")
public class UserController {
	private static final String  APPID="wx1341463c2dca02ba";
	private static final String  APPSECRET="7679103275a4ac992a3a834655ea2c90";
	
	@Autowired
	 private TraineeImpl traineeImpl;
 
	@Autowired
	private  SignImpl    signImpl;
	@Autowired
	private MarkImpl    markImpl;
	@Autowired
	private NoticeCourseImpl noticeCourseImpl;
	@Autowired
	private NoticeImpl   noticeImpl;
 
	
	//cookie失效 重新添加
	@RequestMapping(value="/addcookie",method={RequestMethod.POST,RequestMethod.GET})
	public  ModelAndView addcookie(Model model, HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		String code=request.getParameter("code");
		String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APPID
				+ "&secret="+APPSECRET
				+ "&code="+code
				+ "&grant_type=authorization_code";
		JSONObject jsonObject=WeixinUtil.doGetStr(url);
		String openid=jsonObject.getString("openid");
		String access_token=jsonObject.getString("access_token");
		HttpSession session=request.getSession();
		
		session.setAttribute("openid", openid);
		session.setAttribute("access_token", access_token);
		
		//将得到的openid存入cookie中
		Cookie cookie=new Cookie("vx_openid", openid);
		//设置Cookie的有效期为1年
		cookie.setMaxAge(365*24*60*60);
		cookie.setPath("/");
		//将cookie对象添加到response对象中，这样服务器在输出response对象中的内容时就会把cookie也输出到客户端浏览器
		response.addCookie(cookie);
		

		
		 //找不到cookie为vx_openid的记录，所以是第一次登陆重定向至validate.action进行授权登陆
		return new ModelAndView(new RedirectView("notice/querysigns.action"));
	}
	
	//登陆验证通过后通过openid向数据库中查找详细用户信息

	
	@RequestMapping("/cookievalidate")//用于cookie失效重新授权
	public void cookievalidate(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String backurl="http://nonmin.applinzi.com/user/addcookie.action";
		//String backurl="http://n167337a93.iask.in/weiApp/user/addcookie.action";
		String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+APPID
				+ "&redirect_uri="+URLEncoder.encode(backurl)
				+ "&response_type=code"
				+ "&scope=snsapi_userinfo"
				+ "&state=STATE#wechat_redirect";
		response.sendRedirect(url);
		
	}
	
	@RequestMapping("/validate")//授权登录
	public void validate(HttpServletRequest request, HttpServletResponse response) throws IOException{
		 String backurl="http://nonmin.applinzi.com/user/getinfo.action";
		//String backurl="http://n167337a93.iask.in/weiApp/user/getinfo.action";
		String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+APPID
				+ "&redirect_uri="+URLEncoder.encode(backurl)
				+ "&response_type=code"
				+ "&scope=snsapi_userinfo"
				+ "&state=STATE#wechat_redirect";
		response.sendRedirect(url);
		
	}
	
	
	@RequestMapping("/getinfo")//数据库判断是否存在该用户  1.存在更新账户登陆 2.不存在注册
	public ModelAndView getinfo(HttpServletRequest request,HttpServletResponse response) throws Exception{
		request.setCharacterEncoding("UTF-8");
		HttpSession session=request.getSession();
		String code=request.getParameter("code");
		String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APPID
				+ "&secret="+APPSECRET
				+ "&code="+code
				+ "&grant_type=authorization_code";
		JSONObject jsonObject=WeixinUtil.doGetStr(url);
		String openid=jsonObject.getString("openid");
		String access_token=jsonObject.getString("access_token");
		
		String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token
				+ "&openid="+openid
				+ "&lang=zh_CN";
		JSONObject user=WeixinUtil.doGetStr(infoUrl);//获取用户详细信息
	
		session.setAttribute("openid", openid);//将openid存入回话中
		session.setAttribute("access_token", access_token);
		
        Trainee trainee= traineeImpl.selectByPrimaryKey(openid);
		
		ModelAndView modelAndView=new ModelAndView();
		if(trainee!=null){
			//更新操作
			trainee.setImg(user.getString("headimgurl"));
			traineeImpl.updateImg(trainee);
			
			if(trainee.getState()==0){
				List<Integer> noticeid=signImpl.selectNoticeid( openid);
			modelAndView.addObject("user", trainee);
			modelAndView.addObject("noticeid", noticeid);
			modelAndView.setViewName("login/login1");
			} 
			else if(trainee.getState()==1){
				List<Integer> noticeidmark=noticeImpl.findnoticeidExistsBytidmark(openid);
				List<Integer> noticeidsign=noticeImpl.findnoticeidExistsBytidsign(openid);
				modelAndView.addObject("user", trainee);
				modelAndView.addObject("noticeidmark", noticeidmark);
				modelAndView.addObject("noticeidsign", noticeidsign);
				modelAndView.setViewName("login/login2");
			}
		
		}
		
		else{
			
			modelAndView.setViewName("login/register");
		}
		return modelAndView;
		
		
	}
	@RequestMapping(value="/register",method={RequestMethod.POST,RequestMethod.GET})
	public String register(HttpServletRequest request, HttpServletResponse response  ,Model model,@RequestParam(value="id",required=true) Integer user_id) throws Exception {
		HttpSession session=request.getSession();
		
		String openid=(String) session.getAttribute("openid");
		String access_token=(String) session.getAttribute("access_token");
		String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token
				+ "&openid="+openid
				+ "&lang=zh_CN";
		JSONObject user=WeixinUtil.doGetStr(infoUrl);
		
		//将得到的openid存入cookie中
		Cookie cookie=new Cookie("vx_openid", openid);
		   //设置Cookie的有效期为1年
	     cookie.setMaxAge(365*24*60*60);
	     cookie.setPath("/");
		//将cookie对象添加到response对象中，这样服务器在输出response对象中的内容时就会把cookie也输出到客户端浏览器
	     response.addCookie(cookie);
		
		 
		int sexflag=user.getInt("sex");
		String sex;
		if(sexflag==1)
			sex="男";
		else if(sexflag==2)
			sex="女";
		else
			sex="未知";
		 
		String address=user.getString("country")+user.getString("province")+user.getString("city");
		 
		
		
		Trainee trainee=new Trainee();
		trainee.setId(user.getString("openid"));
		trainee.setName(user.getString("nickname"));
		trainee.setSex(sex);
		trainee.setAddress( address);
		trainee.setImg(user.getString("headimgurl"));
		if(user_id==1){
			trainee.setState(0);
		}
		else if(user_id==2){
			trainee.setState(1);
		}
		
		Trainee trainee2=   traineeImpl.selectByPrimaryKey(openid);
		List<Integer> noticeid=signImpl.selectNoticeid( openid);
		model.addAttribute("noticeid", noticeid);
		List<Integer> noticeidmark=noticeImpl.findnoticeidExistsBytidmark(openid);
		List<Integer> noticeidsign=noticeImpl.findnoticeidExistsBytidsign(openid);
		model.addAttribute("noticeidmark", noticeidmark);
		model.addAttribute("noticeidsign", noticeidsign);
		if(trainee2==null){
			int result=traineeImpl.insert(trainee);
			if(result==1){
				if(user_id==1){
					model.addAttribute("user", trainee);
					return "login/login1";
				}
				else if(user_id==2){
					model.addAttribute("user", trainee);
					return "login/login2";
				}
			}
			else
				return "error";	
		}
		else{
			model.addAttribute("user", trainee2);
			if(user_id==1){
				return "login/login1";
			}
			else if(user_id==2){
				return "login/login2";
			}
		}
		
		return "error";
		
	}
	
	
	@RequestMapping(value="/ajaxtrainee",method={RequestMethod.POST,RequestMethod.GET} )//学员通过培训期号查询其课程成绩
	public void ajaxtrainee(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="noticeid",required=true) Integer noticeid ) throws Exception{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
	
		 HttpSession session=request.getSession();
		 String openid=(String) session.getAttribute("openid");
		
		MarkKey markKey=new MarkKey();
		markKey.setNoticeId( noticeid);
		markKey.setTraineeId(openid);
		List<Mark> marks=markImpl.selectByTran(markKey);
		String result=null;
		
		result="<table border='1' width=100%   ><tr><th>课程名</th><th>成绩</th></tr>";
		
		for(Mark mark:marks){
			result+="<tr><td>"+mark.getCourse().getName()+"</td><td>"+mark.getScore()+"</td></tr>";
		}
		result+="</table>";
		PrintWriter out=response.getWriter();
		out.print(result);
        out.flush();
        out.close();
	}
	
	@RequestMapping(value="/ajaxteach",method={RequestMethod.POST,RequestMethod.GET} )//教员通过 培训期号和学员id查询其课程成绩 
	public void ajaxteach(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="noticeid",required=true) Integer noticeid , @RequestParam(value="traineeid",required=true) String traineeid) throws Exception{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		MarkKey markKey=new MarkKey();
		markKey.setNoticeId( noticeid);
		markKey.setTraineeId(traineeid);
		List<Mark> marks=markImpl.selectByTran(markKey);
		String result=null;
		
		result="<table border='1' width=100%   ><tr><th>课程名</th><th>成绩</th></tr>";
		
		for(Mark mark:marks){
			result+="<tr><td>"+mark.getCourse().getName()+"</td><td>"+mark.getScore()+"</td></tr>";
		}
		result+="</table>";
		PrintWriter out=response.getWriter();
		out.print(result);
        out.flush();
        out.close();
	}
	@RequestMapping(value="/ajaxteasearch",method={RequestMethod.POST,RequestMethod.GET})//返回学员id,姓名，课程id,名称
	public void ajaxteasearch( HttpServletRequest request ,HttpServletResponse response, @RequestParam(value="noticeid",required=true) Integer noticeid) throws Exception{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		List<SignKey> signKeys= signImpl.selectTrainee(noticeid);
		List<NoticourseKey> noticourseKeys=noticeCourseImpl.selectCourse(noticeid);
		String result="";
		String tid="";
		String tname="";
		String cid="";
		String cname="";
		for (SignKey signKey : signKeys) {
			tid+=signKey.getTraineeId()+",";
	        tname+=signKey.getTrainee().getName()+",";
		}
		for (NoticourseKey noticourseKey : noticourseKeys) {
			cid+=noticourseKey.getcId()+",";
			cname+=noticourseKey.getCourse().getName()+",";
		}
		tid=tid.substring(0, tid.length()-1);
		tname=tname.substring(0, tname.length()-1);
		cid=cid.substring(0, cid.length()-1);
		cname=cname.substring(0, cname.length()-1);
		result=tid+";"+tname+";"+cid+";"+cname;
		PrintWriter out=response.getWriter();
		out.print(result);
	    out.flush();
	    out.close();	
	}
	
	@RequestMapping(value="/ajaxteachinsert",method={RequestMethod.POST,RequestMethod.GET} )//教员通过 培训期号,学员id,课程id录入成绩
	public void ajaxteachinsert(HttpServletRequest request,HttpServletResponse response, @RequestParam(value="noticeid",required=true) Integer noticeid , @RequestParam(value="traineeid",required=true) String traineeid,@RequestParam(value="courseid",required=true) Integer courseid, @RequestParam(value="score",required=true) Integer score) throws Exception{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		Mark record=new Mark();
		record.setcId(courseid);
		record.setNoticeId(noticeid);
		record.setTraineeId(traineeid);
		record.setScore(score);
	     int i=markImpl.insert(record);
	     String result=null;
	     if(i==1)
	    	 result="插入成功!";
	     else
	    	 result="请勿重复插入";
		PrintWriter out=response.getWriter();
		out.print(result);
        out.flush();
        out.close();
	}

}
